.pragma library

var _db;

function openDB()
{
    _db = openDatabaseSync("xREL", "1.0", "xREL DB", 1000);

    //_db.transaction( function(tx) { tx.executeSql('DROP TABLE settings;'); } );
    //_db.transaction( function(tx) { tx.executeSql('DROP TABLE filter;'); } );

    createAuthTable();
    createReleaseFilterTable();
    createSettingsTable();
}

function createAuthTable()
{
    _db.transaction(
                function(tx){
                    tx.executeSql('CREATE TABLE IF NOT EXISTS auth(accessToken TEXT, accessTokenSecret TEXT)');
                }
                )
}

function createReleaseFilterTable()
{
    _db.transaction(
                function(tx){
                    tx.executeSql('CREATE TABLE IF NOT EXISTS filter(filterId TEXT, name TEXT)');
                }
                )
}

function createSettingsTable()
{
    _db.transaction(
                function(tx){
                    tx.executeSql('CREATE TABLE IF NOT EXISTS settings(loggedIn TEXT, name TEXT, filterDate LONG)');
                }
                )
}

function hasCredentials() {
    return getCredentials()["token"] !== "";
}

function getCredentials() {
    var credentials = new Object;
    credentials["token"] = "";
    credentials["secret"] = "";
    _db.transaction(
                function(tx) {
                    var rs = tx.executeSql('SELECT * FROM auth');
                    if (rs.rows.length > 0) {
                        credentials["token"] = rs.rows.item(0).accessToken;
                        credentials["secret"] = rs.rows.item(0).accessTokenSecret;
                    }

                }
                );

    return credentials;
}

function getReleaseFilter(model) {
    var now = new Date().getTime();
    var filterDate = parseInt(getSettings()["filterDate"]) + 24*60*60*1000;

    if(getSettings()["filterDate"] === undefined || now > filterDate)
        updateReleaseFilter();

    var filterList = new Object();
    _db.transaction(
                function(tx) {
                    var rs = tx.executeSql('SELECT * FROM filter');
                    for(var i = 0; i < rs.rows.length; i++) {
                        filterList[rs.rows.item(i).filterId] = rs.rows.item(i).name
                        if(model !== undefined)
                            model.append(rs.rows.item(i));
                    }
                }
                );

    return filterList;
}

function getSettings() {
    var settings = new Object;
    settings["loggedIn"] = "";
    _db.transaction(
                function(tx) {
                    var rs = tx.executeSql('SELECT * FROM settings');
                    if (rs.rows.length > 0) {
                        for(var prop in rs.rows.item(0)) {
                            settings[prop] = rs.rows.item(0)[prop];
                        }
                    }
                }
                );

    return settings;
}

function saveCredentials(accessToken, accessTokenSecret) {
    if (!accessToken || !accessTokenSecret)
        return;

    clearCredentials();
    _db.transaction(
                function(tx) {
                    tx.executeSql('INSERT INTO auth VALUES(?,?)', [accessToken, accessTokenSecret]);
                }
                );
    console.log("Credentials saved.");
}

function updateReleaseFilter() {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "http://api.xrel.to/api/release/filters.json");
    xhr.onreadystatechange = function() {
                if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
                    var jsonOnly = xhr.responseText.substring(xhr.responseText.indexOf("{"), xhr.responseText.lastIndexOf("}")+1);
                    var jsonObject = JSON.parse(jsonOnly);
                    var filterList = new Array();
                    for(var index in jsonObject.payload) {
                        filterList.push(jsonObject.payload[index]);
                    }
                    saveReleaseFilter(filterList);
                }
            }

    xhr.send();
}

function saveReleaseFilter(filterList) {
    if(filterList.length === 0)
        return;

    var settings = new Object;
    settings["filterDate"] = new Date().getTime();
    saveSettings(settings);

    clearReleaseFilter();
    _db.transaction(
                function(tx) {
                    for(var i=0; i<filterList.length; i++)
                        tx.executeSql('INSERT INTO filter VALUES(?,?)', [filterList[i].id, filterList[i].name]);

                }
                );
    console.log("Filter saved.");
}

function saveSettings(settings) {
    var oldSettings = getSettings();

    for(var prop in settings) {
        oldSettings[prop] = settings[prop];
    }

    clearSettings();
    _db.transaction(
                function(tx) {
                    tx.executeSql('INSERT INTO settings VALUES(?,?,?)', [oldSettings["loggedIn"], oldSettings["text"], oldSettings["filterDate"]]);
                }
                );
    console.log("Settings saved.");
}

function clearCredentials() {
    _db.transaction( function(tx) { tx.executeSql('DELETE FROM auth;'); } );
    console.log("Credentials deleted.");
}

function clearReleaseFilter() {
    _db.transaction( function(tx) { tx.executeSql('DELETE FROM filter;'); } );
}

function clearSettings() {
    _db.transaction( function(tx) { tx.executeSql('DELETE FROM settings;'); } );
}
